<template>
  <div>
     <van-field
        v-model="telCode"
        center
        clearable
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button :disabled="btnFlag" size="small" @click="sendCode" type="default">{{ text }}</van-button>
        </template>
      </van-field>
     <van-button round @click="step" :disabled="flag" type="danger" block>下一步</van-button>
  </div>
</template>

<script>
import Vue from 'vue'
import { Field, Button, Toast } from 'vant'
import { dosendmsgcode, docheckcode } from './../../api/user'
Vue.use(Field)
Vue.use(Button)
Vue.use(Toast)
export default {
  computed: {
    btnFlag () {
      return this.time > 0 && this.time < 10
    },
    flag () {
      return this.telCode === ''
    }
  },
  mounted () {
    this.sendCode()
  },
  data () {
    return {
      tel: '',
      telCode: '',
      time: 10,
      text: '发送验证码',
      timer: null
    }
  },
  methods: {
    async step () {
      const res = await docheckcode({
        tel: localStorage.getItem('tel'),
        telcode: this.telCode
      })
      // console.log(res.data)
      if (res.data.code === '10007') {
        Toast('验证码输入有误')
      } else {
        this.$router.push('/register/step3')
      }
    },
    sendCode () {
      this.timer = setInterval(() => {
        this.text = '重新发送(' + this.time + ')'
        this.time--
        if (this.time === 0) {
          clearInterval(this.timer)
          this.text = '发送验证码'
          this.time = 10
        }
      }, 1000)
      // 发送短信验证码
      dosendmsgcode({ tel: localStorage.getItem('tel') })
        .then(res => {
          console.log(res.data)
        })
    }
  }
}
</script>
